package com.kmproject.haifu.mvp.presenter;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.irozon.library.HideKey;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.CustomPopupWindow;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.RxUtils;
import com.kmproject.haifu.app.utils.TimeUtils;
import com.kmproject.haifu.mvp.contract.HouseRentingShowMainContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseMainBean;
import com.kmproject.haifu.mvp.model.entity.resbean.HouseRentListParmarBean;
import com.kmproject.haifu.mvp.model.entity.resbean.PopuWindowSelectSearchBean;
import com.kmproject.haifu.mvp.ui.activity.HouseRentingShowDuanZuListActivity;
import com.kmproject.haifu.mvp.ui.adapter.PopuwindowSearchAdapter;
import com.kmproject.haifu.mvp.ui.adapter.PopuwindowSearchNewAdapter;
import com.xw.repo.XEditText;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/03/2019 11:31
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class HouseRentingShowMainPresenter extends BasePresenter<HouseRentingShowMainContract.Model, HouseRentingShowMainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    CustomPopupWindow customPopupWindow;
    int mtype=1;
    PopuwindowSearchNewAdapter popuwindowSearchNewAdapter = null;
    @Inject
    public HouseRentingShowMainPresenter(HouseRentingShowMainContract.Model model, HouseRentingShowMainContract.View rootView) {
        super(model, rootView);
    }
    /**
     * 获取租房发布类型
     * @param
     * @param
     */
    public void  dictList() {

        mModel.dictList(Api.HOUSE_CATEGORY,"").compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HousePayWayBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HousePayWayBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean))
                        {
                            mRootView.dictListSuccess(listResultBean.getData());
                        }else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }


    /**
     * 获取出租房展示列表
     * @param houseRentListParmarBean
     */
    public void getHouseRentList( HouseRentListParmarBean houseRentListParmarBean){

        mModel.getHouseRentList(AppUtil.entityToMap(houseRentListParmarBean)).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HouseRentListShowBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HouseRentListShowBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean))
                        {
                            mRootView.getHouseRentListSuccess(listResultBean);
                        }else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }

                    }
                });
    }
    /**
     * 初始化数据
     *
     * @return
     */
    public List<HouseMainBean> getDatas() {
        List<HouseMainBean> houseMainBeans = new ArrayList<>();
        List<HouseMainBean.HouseMainItem> houseMainItems1 = new ArrayList<>();
        houseMainItems1.add(new HouseMainBean.HouseMainItem("zz", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_zz), R.drawable.houserentingshow_zhengzu_icon, "rentShow"));
        houseMainItems1.add(new HouseMainBean.HouseMainItem("hz", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_hz), R.drawable.houserentingshow__hezu_icon, "rentShow"));
        houseMainItems1.add(new HouseMainBean.HouseMainItem("dz", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_dz), R.drawable.houserentingshow_duanzu_icon, "rentShow"));
        HouseMainBean houseMainBean1 = new HouseMainBean(ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_title_zz), houseMainItems1);

        List<HouseMainBean.HouseMainItem> houseMainItems2 = new ArrayList<>();
        houseMainItems2.add(new HouseMainBean.HouseMainItem("sp", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_sp), R.drawable.houserentingshow_shangpu_icon, "rentShow"));
        houseMainItems2.add(new HouseMainBean.HouseMainItem("xzl", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_xzl), R.drawable.houserentingshow_xiezilou_icon, "rentShow"));
        houseMainItems2.add(new HouseMainBean.HouseMainItem("syzr", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_syzr), R.drawable.houserentingshow_shengyizhuanrang_icon, "rentShow"));
        houseMainItems2.add(new HouseMainBean.HouseMainItem("qt", ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_qt), R.drawable.houserentingshow_qita_icon, "rentShow"));
        HouseMainBean houseMainBean2 = new HouseMainBean(ArmsUtils.getString(mAppManager.getCurrentActivity(), R.string.houserentingshow_sydc), houseMainItems2);

        houseMainBeans.add(houseMainBean1);
        houseMainBeans.add(houseMainBean2);

        return houseMainBeans;
    }

    /**
     * 控制popu 搜索控制
     */
    public void showPopuWindowToSearch(Activity activity, View view,List<HousePayWayBean> housePayWayBeans) {
        HideKey.initialize(activity, view);
         customPopupWindow = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.popuwindow_selectsearchaddress)).parentView(view)
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isHaveBackGround(false).build();
        View view1 = customPopupWindow.getContentView();
        PopuwindowViewHold popuwindowViewHold=new PopuwindowViewHold(view1);
        contrlShow(popuwindowViewHold,1,activity,housePayWayBeans);
        popuwindowViewHold.popuwindowSelectsearchaddressXext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
              if (s.toString().trim().length()<1)
              {
                  //输入内容小于1 的时候显示第一个搜索
                  contrlShow(popuwindowViewHold,1,activity,housePayWayBeans);
              }else if (s.toString().trim().length()>0&&mtype==1){
                  //s.toString().trim().length()<2避免多次刷新同样的数据
                  //有搜索内容的时候显示第二个搜索
                  contrlShow(popuwindowViewHold,2,activity,housePayWayBeans);
              }
            }
        });

        popuwindowViewHold.popuwindowSelectsearchaddressCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindow.dismiss();
            }
        });
                customPopupWindow.show();
    }

    /**
     * 控制布局显示
     * @param type
     */
    private void contrlShow(PopuwindowViewHold popuwindowViewHold,int type,Activity activity,List<HousePayWayBean> housePayWayBeans)
    {

        mtype=type;
        if (type==1)
        {
            popuwindowViewHold.popuwindowSelectsearchaddressLay1.setVisibility(View.VISIBLE);
            popuwindowViewHold.popuwindowSelectsearchaddressLay2.setVisibility(View.GONE);
            popuwindowViewHold.popuwindowSelectsearchaddressRecyclerView1.setLayoutManager(new LinearLayoutManager(activity));
            List<PopuWindowSelectSearchBean> popuWindowSelectSearchBeans = DataHelper.getDeviceData(activity, AppConstant.rent_Search_history);

            if (popuWindowSelectSearchBeans == null || popuWindowSelectSearchBeans.isEmpty()) {
                popuwindowSearchNewAdapter = new PopuwindowSearchNewAdapter(null);
                popuwindowViewHold.popuwindowSelectsearchaddressRecyclerView1.setAdapter(popuwindowSearchNewAdapter);
                popuwindowSearchNewAdapter.setEmptyView(AppUtil.setEmptyView(activity, "没有搜索记录", "", null, true));
            }else {
                popuwindowSearchNewAdapter = new PopuwindowSearchNewAdapter(popuWindowSelectSearchBeans);
                popuwindowViewHold.popuwindowSelectsearchaddressRecyclerView1.setAdapter(popuwindowSearchNewAdapter);
            }
            popuwindowSearchNewAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
            popuwindowSearchNewAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Intent intent =new Intent(AppManager.getAppManager().getCurrentActivity(),HouseRentingShowDuanZuListActivity.class);
                    intent.putExtra("type",popuwindowSearchNewAdapter.getData().get(position).getHousePayWayBean().getCategory());
                    intent.putExtra("HousePayWayBean",popuwindowSearchNewAdapter.getData().get(position).getHousePayWayBean());
                    intent.putExtra("searchContent",popuwindowSearchNewAdapter.getData().get(position).getContent());
                    ArmsUtils.startActivity(intent);
                    customPopupWindow.dismiss();
                }
            });
        }else {
            popuwindowViewHold.popuwindowSelectsearchaddressLay1.setVisibility(View.GONE);
            popuwindowViewHold.popuwindowSelectsearchaddressLay2.setVisibility(View.VISIBLE);
            popuwindowViewHold.popuwindowSelectsearchaddressRecyclerView2.setLayoutManager(new LinearLayoutManager(activity));


            PopuwindowSearchAdapter popuwindowSearchAdapter = new PopuwindowSearchAdapter(housePayWayBeans);
            popuwindowViewHold.popuwindowSelectsearchaddressRecyclerView2.setAdapter(popuwindowSearchAdapter);
            popuwindowSearchAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
            popuwindowSearchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    List<PopuWindowSelectSearchBean> popuWindowSelectSearchBeans = DataHelper.getDeviceData(activity, AppConstant.rent_Search_history);
                    if (popuWindowSelectSearchBeans==null)
                    {
                        popuWindowSelectSearchBeans=new ArrayList<>();
                    }
                    if (popuWindowSelectSearchBeans.size()>10)
                    {
                        //搜索记录保持最新10条
                        popuWindowSelectSearchBeans.remove(0);
                    }
                    UserBean userBean=DataHelper.getDeviceData(activity,AppConstant.USER_INFO);
                    if (userBean!=null&&! TextUtils.isEmpty(userBean.getMobile()))
                    {
                        popuWindowSelectSearchBeans.add(new PopuWindowSelectSearchBean(TimeUtils.date2String(new Date()),popuwindowViewHold.popuwindowSelectsearchaddressXext.getText().toString(),userBean.getMobile(),housePayWayBeans.get(position)));
                    }else {
                        popuWindowSelectSearchBeans.add(new PopuWindowSelectSearchBean(TimeUtils.date2String(new Date()),popuwindowViewHold.popuwindowSelectsearchaddressXext.getText().toString(),"",housePayWayBeans.get(position)));

                    }
                    DataHelper.saveDeviceData(activity,AppConstant.rent_Search_history,popuWindowSelectSearchBeans);
                    Intent intent =new Intent(AppManager.getAppManager().getCurrentActivity(),HouseRentingShowDuanZuListActivity.class);
                    intent.putExtra("type",housePayWayBeans.get(position).getCategory());
                    intent.putExtra("HousePayWayBean",housePayWayBeans.get(position));
                    intent.putExtra("searchContent",popuwindowViewHold.popuwindowSelectsearchaddressXext.getText().toString());
                    ArmsUtils.startActivity(intent);
                    customPopupWindow.dismiss();
                }
            });
        }
        popuwindowViewHold.popuwindowSelectsearchaddressClearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataHelper.saveDeviceData(activity,AppConstant.rent_Search_history,null);
                ArmsUtils.makeText(activity,"清除成功");
                popuwindowSearchNewAdapter.setEmptyView(AppUtil.setEmptyView(activity, "没有搜索记录", "", null, true));

            }
        });
    }

    /**
     * 得到类型数据源
     * @return
     */
//    private List<PopuWindowSelectSearchBean> getData()
//    {
//        List<PopuWindowSelectSearchBean> popuWindowSelectSearchBeans=new ArrayList<>();
//        popuWindowSelectSearchBeans.add(new PopuWindowSelectSearchBean("整租","zz"));
//        popuWindowSelectSearchBeans.add(new PopuWindowSelectSearchBean("合租","hz"));
//        popuWindowSelectSearchBeans.add(new PopuWindowSelectSearchBean("短租","dz"));
//        return popuWindowSelectSearchBeans;
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public static class PopuwindowViewHold {

        @BindView(R.id.popuwindow_selectsearchaddress_clearAll)
        TextView popuwindowSelectsearchaddressClearAll;
        @BindView(R.id.popuwindow_selectsearchaddress_RecyclerView1)
        RecyclerView popuwindowSelectsearchaddressRecyclerView1;
        @BindView(R.id.popuwindow_selectsearchaddress_lay1)
        LinearLayout popuwindowSelectsearchaddressLay1;
        @BindView(R.id.popuwindow_selectsearchaddress_RecyclerView2)
        RecyclerView popuwindowSelectsearchaddressRecyclerView2;
        @BindView(R.id.popuwindow_selectsearchaddress_lay2)
        LinearLayout popuwindowSelectsearchaddressLay2;
        @BindView(R.id.popuwindow_selectsearchaddress_xext)
        XEditText popuwindowSelectsearchaddressXext;
        @BindView(R.id.popuwindow_selectsearchaddress_cancel)
        TextView popuwindowSelectsearchaddressCancel;

        public PopuwindowViewHold(View view) {
//            R.layout.popuwindow_selectsearchaddress
            ButterKnife.bind(this, view);
        }
    }
}
